import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/userStore'

// 路由组件懒加载
const MainLayout = () => import('@/components/layout/MainLayout.vue')
const HomeView = () => import('@/views/HomeView.vue')
const LoginView = () => import('@/views/LoginView.vue')
const RegisterView = () => import('@/views/RegisterView.vue')
const ForgotPasswordView = () => import('@/views/ForgotPasswordView.vue')
const PublishView = () => import('@/views/PublishView.vue')
const GoodsDetailView = () => import('@/views/GoodsDetailView.vue')
const CollectsView = () => import('@/views/CollectsView.vue')
const MyGoodsView = () => import('@/views/MyGoodsView.vue')
const ProfileView = () => import('@/views/ProfileView.vue')
const NotFoundView = () => import('@/views/NotFoundView.vue')

const routes = [
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: HomeView,
        meta: { title: '首页' }
      },
      {
        path: 'publish',
        name: 'Publish',
        component: PublishView,
        meta: { title: '发布商品', requiresAuth: true }
      },
      {
        path: 'goods/:id',
        name: 'GoodsDetail',
        component: GoodsDetailView,
        meta: { title: '商品详情' }
      },
      {
        path: 'collects',
        name: 'Collects',
        component: CollectsView,
        meta: { title: '我的收藏', requiresAuth: true }
      },
      {
        path: 'my-goods',
        name: 'MyGoods',
        component: MyGoodsView,
        meta: { title: '我的商品', requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: ProfileView,
        meta: { title: '个人中心', requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: { title: '登录', requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterView,
    meta: { title: '注册', requiresGuest: true }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: ForgotPasswordView,
    meta: { title: '找回密码', requiresGuest: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFoundView,
    meta: { title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = `${to.meta.title} - 江西农业大学二手交易平台`
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
    return
  }
  
  // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
  if (to.meta.requiresGuest && userStore.isLoggedIn) {
    next('/')
    return
  }
  
  next()
})

export default router